# -*- coding: utf-8 -*-
# @Author : zhaochen
# @Date   : 2019/4/13
# @File   : TX11_IncomeTaxGrowthRate_SC.py
# @E-mail : zhaochen@bbdservice.com


'''eof
name:所得税增长率
code:TX11_IncomeTaxGrowthRate_SC
tableName:
columnName:
groups:税务模块
dependencies:TX_SC_DSJ
type:常用指标
datasourceType:在线指标
description:
eof'''


import json
import re
import sys
import datetime
import pandas as pd
import math

reload(sys)
sys.setdefaultencoding('utf-8')


def inquireIsReportNo(data):
    """
    判断是否存在reportNo
    :param data:
    :return:True/False
    """
    try:

        is_reportNo = True if len(data.get("reportNo")) > 0 else False

    except:
        is_reportNo = False

    return is_reportNo


def formatData(table_Name):
    """
    获取数据
    :param table_Name:字典keys
    :return:[{}]
    """
    try:
        data = TX_SC_DSJ["data"].get(table_Name)
        return data if isinstance(data, list) and len(data) > 0 else [{}]

    except:
        return [{}]

def dataPre(dataList=None, key=None):
    """
    对list里面的列表去重月份不标准的
    :param dataList:
    :param key:
    :return:
    """
    dataListTemp = dataList
    data = []
    for i in range(len(dataListTemp)):
        temp = dataListTemp[i].get(key)
        try:
            temp = int(temp)
        except:
            temp = None
            pass

        if temp:
            data.append(dataListTemp[i])
        else:
            pass

    if len(data) == 0:
        data = [{}]
    else:
        pass

    return data

def convertDataType(data_value, data_type):
    """
    数据格式转换
    :param data_value:
    :param data_type: float/int/str/date_time
    :return:
    """
    data_value = str(data_value)
    return_data = None
    # float
    if data_type == 'float':
        try:
            return_data = float(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # int
    elif data_type == 'int':
        try:
            return_data = int(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # str
    elif data_type == 'str':
        try:
            return_data = str(data_value) if len(data_value) >= 0 else None
        except:
            return_data = None
    # date_time
    elif data_type == 'date_time':
        r = re.compile(r'\D+')
        try:
            return_data = datetime.datetime.strptime(data_value, '%Y.%m.%d').strftime('%Y-%m-%d')
        except:
            try:
                return_data = datetime.datetime.strptime(data_value, '%Y-%m-%d').strftime('%Y-%m-%d')
            except:
                try:
                    return_data = datetime.datetime.strptime(data_value, '%Y/%m/%d').strftime('%Y-%m-%d')
                except:
                    try:
                        data_value = r.sub('', data_value)
                        return_data = datetime.datetime.strptime(data_value, '%Y%m%d').strftime('%Y-%m-%d')
                    except:
                        return_data = None

    return return_data

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--','NaN','nan']

def incomeTaxDataMerge(syptQysdsNd, syptQysdsA1, putBackYear=2, CcrDate=None):
    """
    所得税纳税数据拆分为近2年的月度数据

    :param syptQysdsNd: 年度汇算清缴表，类型[{}]
    :param syptQysdsA1: A1表，类型[{}]
    :param putBackYear: 回推时间，默认为2年
    :return: IncomeTaxData为Series
    """
    # 字典排序
    syptQysdsNd = dataPre(syptQysdsNd, key='ND')
    syptQysdsA1 = dataPre(syptQysdsA1, key='YF')
    # 生成时间轴
    dateIndexList = []
    if CcrDate is None:
        CcrYearMonth = datetime.datetime.now().strftime('%Y-%m-%d')[:7]
        CcrDate = CcrYearMonth + '-01'
        StartDateTmp = str(datetime.datetime.now().year - putBackYear) + CcrDate[4:]
        StartDate = StartDateTmp[:7] + '-01'
    else:
        CcrYear = datetime.datetime.strptime(convertDataType(CcrDate, 'date_time'), '%Y-%m-%d').date().year
        CcrDate = convertDataType(CcrDate, 'date_time')[:7] + '-01'
        StartDate = str(CcrYear - putBackYear) + convertDataType(CcrDate, 'date_time')[4:]

    dateSet = pd.date_range(StartDate, CcrDate, freq='M')
    for i in dateSet:
        year = i.date().year
        month = i.date().month
        dateIndexList.append(str(year) + str(month))

    IncomeTaxData = pd.Series(None, index=dateIndexList)

    if syptQysdsNd == [{}] and syptQysdsA1 == [{}]:
        return u'缺失值'
    else:
        # 使用年度汇算清缴表
        if syptQysdsNd != [{}]:
            syptQysdsNd = sorted(syptQysdsNd, key=lambda x: int(x['ND']))
            for i in range(len(syptQysdsNd)):
                ND = convertDataType(syptQysdsNd[i].get('ND'), 'int')
                NDYF = [str(datetime.datetime.now().year-1),
                        str(datetime.datetime.now().year-2),
                        str(datetime.datetime.now().year-3)]
                if ND and str(ND) in NDYF:
                    YNSDSE = convertDataType(syptQysdsNd[i].get('YNSDSE'), 'float')
                    if YNSDSE is not None:
                        for j in IncomeTaxData.index:
                            if str(ND) in j and math.isnan(IncomeTaxData.loc[j]):
                                IncomeTaxData.loc[j] = YNSDSE/12
                            else:
                                pass
                    else:
                        pass
                else:
                    pass
        # 使用A1表(默认为只有按季度缴纳)
        if syptQysdsA1 != [{}]:
            syptQysdsA1 = sorted(syptQysdsA1, key=lambda x: int(x['YF']))
            for i in range(len(syptQysdsA1)):
                ND = convertDataType(syptQysdsA1[i].get('ND'), 'int')
                YF = convertDataType(syptQysdsA1[i].get('YF'), 'int')
                if ND and YF:
                    NDYF = str(ND) + str(YF)
                    if NDYF in IncomeTaxData.index:
                        YNSSDE = convertDataType(syptQysdsA1[i].get('YNSSDE'), 'float')
                        if YF in [3, 6, 9, 12]:
                            if YNSSDE is not None:
                                # 倒推三个月在时间轴内
                                if ((str(ND) + str(YF)) in IncomeTaxData.index) and ((str(ND) + str(
                                        YF - 1)) in IncomeTaxData.index) and \
                                        ((str(ND) + str(YF - 2)) in IncomeTaxData.index):

                                    # 临近三个月全为空，3个为空
                                    if math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]) \
                                            and math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]) \
                                            and math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 3
                                        IncomeTaxData.loc[str(ND) + str(YF - 1)] = YNSSDE / 3
                                        IncomeTaxData.loc[str(ND) + str(YF - 2)] = YNSSDE / 3
                                    # 临近三个月倒数第3个月非空，2个为空
                                    elif math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]) and \
                                            not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]):
                                        IncomeTaxData.loc[str(ND) + str(YF - 1)] = YNSSDE / 2
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 2
                                    # 临近三个月倒数第2个月非空，2个为空
                                    elif math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]) and \
                                            not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]):
                                        IncomeTaxData.loc[str(ND) + str(YF - 2)] = YNSSDE / 2
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 2
                                    # 临近三个月倒数第三个月非空，1个为空
                                    elif not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 2)]) and \
                                            not math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]) \
                                            and math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE
                                # 倒数最后二个月不在时间轴内
                                elif (str(ND) + str(YF - 2)) not in IncomeTaxData.index and\
                                        ((str(ND) + str(YF - 1)) in IncomeTaxData.index) and ((str(ND) + str(
                                        YF)) in IncomeTaxData.index):
                                    # 倒推两个月都为空
                                    if math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]) and math.isnan(
                                            IncomeTaxData.loc[str(ND) + str(YF - 1)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 3
                                        IncomeTaxData.loc[str(ND) + str(YF - 1)] = YNSSDE / 3
                                    elif math.isnan(IncomeTaxData.loc[str(ND) + str(YF - 1)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 2
                                # 倒数最后一个月不在时间轴内
                                elif (str(ND) + str(YF - 2)) not in IncomeTaxData.index and \
                                        ((str(ND) + str(YF - 1)) not in IncomeTaxData.index) and ((str(ND) + str(
                                        YF)) in IncomeTaxData.index):
                                    if math.isnan(IncomeTaxData.loc[str(ND) + str(YF)]):
                                        IncomeTaxData.loc[str(ND) + str(YF)] = YNSSDE / 3
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
                else:
                    pass
        return IncomeTaxData

#计算所得税年增长率
syptQysdsNd = formatData('syptQysdsNd')
syptQysdsA1 = formatData('syptQysdsA1')
IncomeTax = incomeTaxDataMerge(syptQysdsNd, syptQysdsA1, putBackYear=2, CcrDate=None)

def TX11_IncomeTaxGrowthRate_SC():
    try:
        if len(IncomeTax) <= 3:
            return u'缺失值'
        else:
            for k in range(len(IncomeTax)):
              if(IncomeTax[k] > -99999):
                  IncomeTax[k] = IncomeTax[k]
              else:
               IncomeTax[k] = 0
            result1 = IncomeTax[:12]
            result2 = IncomeTax[12:24]
            sum1 = sum(result1)
            sum2 = sum(result2)
            if sum1 <= 0 or sum2 < 0:
                return u'缺失值'
            else:
                return (round(sum2/sum1 - 1,4))
    except:
        return u'缺失值'


result = TX11_IncomeTaxGrowthRate_SC()